﻿using XCI.Core;

namespace XCI.Helper
{
    /// <summary>
    /// 社会统一信用代码帮助类
    /// </summary>
    public class SocialCreditCodeHelper
    {
        /// <summary>
        /// 社会统一信用代码结果
        /// </summary>
        /// <param name="idcard">社会统一信用代码</param>
        /// <returns>正确的时候返回string.Empty</returns>
        public static BoolResult Validate(string social_credit_code)
        {

            if (string.IsNullOrEmpty(social_credit_code) || social_credit_code.Length != 18)
            {
                return new BoolResult(false, "社会统一信用代码必须是18位。");
            }
            string Ancode; //统一社会信用代码的每一个值
            int Ancodevalue; //统一社会信用代码每一个值的权重 
            int total = 0;
            int[] weightedfactors = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };//加权因子
            string str = "0123456789ABCDEFGHJKLMNPQRTUWXY";
            //不用I、O、S、V、Z 
            for (var i = 0; i < social_credit_code.Length - 1; i++)
            {
                Ancode = social_credit_code.Substring(i, 1);
                Ancodevalue = str.IndexOf(Ancode);
                total += Ancodevalue * weightedfactors[i];
                //权重与加权因子相乘之和 
            }
            int logiccheckcode = 31 - total % 31;
            if (logiccheckcode == 31)
            {
                logiccheckcode = 0;
            }
            var Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
            var Array_Str = Str.Split(',');
            string str_logiccheckcode = Array_Str[logiccheckcode];
            var checkcode = social_credit_code.Substring(17, 1);
            if (str_logiccheckcode.ToString() != checkcode)
            {
                return new BoolResult(false, "不是有效的统一社会信用编码。");
            }
            return BoolResult.True;
        }
    }
}
